package com.guoyh.baseutils.utils.countdowntimer

import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import com.guoyh.baseutils.mylog.Loger
import java.util.*

/**
 * author  dengyuhan
 * created 2017/5/16 11:32
 */
open class CountDownTimerm {

    private var mTimer: Timer? = null
    private var mHandler: Handler

    /**
     * 倒计时时间
     */
    private var mMillisInFuture: Long = 0

    /**
     * 间隔时间
     */
    private var mCountDownInterval: Long = 0

    /**
     * 倒计时剩余时间
     */
    var millisUntilFinished: Long = 0
        private set
    private var mOnCountDownTimerListener: OnCountDownTimerListener? = null
    var timerState = TimerState.FINISH
        private set

    /**
     * @millisInFuture 倒计时时间
     * @countDownInterval 间隔时间
     */
    constructor(millisInFuture: Long, countDownInterval: Long) {
        setMillisInFuture(millisInFuture)
        setCountDownInterval(countDownInterval)
        mHandler = Handler(Looper.myLooper()!!)
    }

    fun start() {
        //防止重复启动 重新启动要先reset再start
        if (mTimer == null && timerState !== TimerState.START) {
            mTimer = Timer()
            mTimer!!.scheduleAtFixedRate(createTimerTask(), 0, mCountDownInterval)
            timerState = TimerState.START
        }
    }

    fun pause() {
        Loger.dd("========暂停")
        if (mTimer != null && timerState === TimerState.START) {
            cancelTimer()
            timerState = TimerState.PAUSE
        }
    }

    fun resume() {
        Loger.dd("========继续")
        if (timerState === TimerState.PAUSE) {
            start()
        }
    }

    fun stop() {
        if (mTimer != null) {
            cancelTimer()
            millisUntilFinished = mMillisInFuture
            timerState = TimerState.FINISH
            mHandler.post {
                if (mOnCountDownTimerListener != null) {
                    mOnCountDownTimerListener!!.onFinish()
                }
            }
        }
    }

    fun reset() {
        if (mTimer != null) {
            cancelTimer()
        }
        millisUntilFinished = mMillisInFuture
        timerState = TimerState.FINISH
    }

    fun cancelTimer() {
        if (mTimer != null) {
            mTimer!!.cancel()
            mTimer!!.purge()
            mTimer = null
        }
    }

    val isStart: Boolean
        get() = timerState === TimerState.START

    val isFinish: Boolean
        get() = timerState === TimerState.FINISH


    private fun setMillisInFuture(millisInFuture: Long) {
        mMillisInFuture = millisInFuture
        millisUntilFinished = mMillisInFuture
    }


    private fun setCountDownInterval(countDownInterval: Long) {
        mCountDownInterval = countDownInterval
    }

    fun setOnCountDownTimerListener(listener: OnCountDownTimerListener): CountDownTimerm {
        mOnCountDownTimerListener = listener
        return this
    }

    /**
     * @param millisInFuture
     * @param countDownInterval
     * @return
     */
    @Deprecated("已更换Timer")
    protected fun createCountDownTimer(
        millisInFuture: Long,
        countDownInterval: Long
    ): CountDownTimer? {
        return null
    }

    protected fun createTimerTask(): TimerTask {
        return object : TimerTask() {
            private var startTime: Long = -1
            override fun run() {
                if (startTime < 0) {
                    //第一次回调 记录开始时间
                    startTime = scheduledExecutionTime() - (mMillisInFuture - millisUntilFinished)
                    mHandler.post(object : Runnable {
                        override fun run() {
                            if (mOnCountDownTimerListener != null) {
                                mOnCountDownTimerListener!!.onTick(millisUntilFinished)
                            }
                        }
                    })
                } else {
                    //剩余时间
                    millisUntilFinished = mMillisInFuture - (scheduledExecutionTime() - startTime)
                    mHandler.post(object : Runnable {
                        override fun run() {
                            if (mOnCountDownTimerListener != null) {
                                mOnCountDownTimerListener!!.onTick(millisUntilFinished)
                            }
                        }
                    })
                    if (millisUntilFinished <= 0) {
                        //如果没有剩余时间 就停止
                        stop()
                    }
                }
            }
        }
    }
}


enum class TimerState {
    START, PAUSE, FINISH
}

interface OnCountDownTimerListener {
    fun onTick(millisUntilFinished: Long)
    fun onFinish()
}